<template>
  <!-- 充放电曲线数据 弹窗 -->
  <a-modal
    v-model:open="visible"
    title="充放电曲线数据"
    @ok="handleOk"
    destroyOnClose
    :width="1000"
    @cancel="cancel"
    centered
  >
    <a-table
      :dataSource="tableData"
      :columns="columns"
      size="small"
      :scroll="{ x: 'max-content' }"
      @resizeColumn="handleResizeColumn"
      :loading="tableLoading"
      :rowKey="(column) => column"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'value1'">
          <span v-param="record.pdId">{{ record.value1 }}</span>
        </template>
        <template v-if="column.key === 'value2'">
          <span v-param="record.pdId">{{ record.value2 }}</span>
        </template>
      </template>
    </a-table>
    <template #footer>
      <div class="footerBar">
        <a-button
          v-hasPermission="'monitorChargeDischargeExportData'"
          class="yellowBtn"
          @click="handleExport"
          @loading="loading"
          >导出</a-button
        >
        <a-button key="submit" type="primary" @click="cancel">关闭</a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import utilsExportFile from "@/utils/exportFile"
import { transformExportData } from "@/utils/common"
const $api = inject("$api")
const props = defineProps({
  detailsDataVisible: {
    type: Boolean,
    default: false,
  },
  chartsTableData: {
    type: Object,
  },
  chartType: {
    type: String,
  },
})
const visible = ref(props.detailsDataVisible)
const emits = defineEmits(["update:detailsDataVisible", "getParamCodePage"])
watch(
  () => props.detailsDataVisible,
  (val) => {
    visible.value = val
    if (val) {
      initTableData()
    }
  }
)
const labelCol = { style: { width: "130px" } }
const tableData = ref([])
const columns = ref([
  {
    title: "数据来源",
    dataIndex: "linkName",
    key: "linkName",
    width: 150,
    resizable: true,
    align: "center",
  },
  {
    title: "时间1",
    dataIndex: "date1",
    key: "date1",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "充放电数据",
    dataIndex: "value1",
    key: "value1",
    width: 120,
    resizable: true,
    align: "center",
    customCell: (record, rowIndex, column) =>
      getCustomCellColour(record, rowIndex, column),
  },
  {
    title: "时间2",
    dataIndex: "date2",
    key: "date2",
    width: 120,
    resizable: true,
    align: "center",
  },
  {
    title: "充放电数据",
    dataIndex: "value2",
    key: "value2",
    width: 150,
    resizable: true,
    align: "center",
    customCell: (record, rowIndex, column) =>
      getCustomCellColour(record, rowIndex, column),
  },
])
const getCustomCellColour = (record, rowIndex, column) => {
  const { isBuild1, isBuild2, isBuild3, isBuild4 } = record

  switch (column.dataIndex) {
    case "value1":
      if (isBuild1) {
        return {
          style: {
            background: `rgba(244, 63, 94, 0.2)`,
          },
        }
      }
      break
    case "value2":
      if (isBuild2) {
        return {
          style: {
            background: `rgba(244, 63, 94, 0.2)`,
          },
        }
      }
      break
  }
}
const cancel = () => {
  emits("update:detailsDataVisible", false)
}
const tableLoading = ref(false)
const exportData = ref([])
const initTableData = () => {
  // 新的数组以存放合并后的结果
  const newlineData = []
  // 转换成便于后续合并的结构 {linkName: {date: lineData}}
  const groupedData = {}
  // 遍历原始数据进行分组

  const chartsTableData = props.chartsTableData.flat()
  for (const item of chartsTableData) {
    if (props.chartType === 1) {
      item.linkName = `${item.linkName}-${item.blockName}`
    } else {
      item.linkName = item.linkName
    }
    item.lineData = item.lineData.map((lineItem) => {
      return {
        ...lineItem,
        pdId: item.pdId, // 将pdId添加到lineData每个对象
      }
    })
  }
  console.log("[ chartsTableData123 ]-101", chartsTableData)
  chartsTableData.forEach((item) => {
    const { linkName, date, lineData, isBuild, blockName } = item
    // 如果还没有链接名的项，初始化
    if (!groupedData[linkName]) {
      groupedData[linkName] = {}
    }
    // 如果还没有日期的项，初始化
    if (!groupedData[linkName][date]) {
      groupedData[linkName][date] = []
    }

    // 将 lineData 添加到对应的链接名和日期下
    const chartLineData = lineData.map((item) => {
      return {
        ...item,
      }
    })
    groupedData[linkName][date] = [...chartLineData]
  })
  console.log("[ groupedData ]-101", groupedData)
  // 组合新的结果
  for (const linkName in groupedData) {
    const dates = Object.keys(groupedData[linkName])
    for (let i = 0; i < dates.length - 1; i++) {
      const currentDateData = groupedData[linkName][dates[i]]
      const nextDateData = groupedData[linkName][dates[i + 1]]
      currentDateData.forEach((currentItem, index) => {
        const nextItem = nextDateData[index]
        if (nextItem) {
          newlineData.push({
            linkName,
            date1: currentItem.dateTime,
            value1: currentItem.value,
            date2: nextItem.dateTime,
            value2: nextItem.value,
            pdId: currentItem.pdId,
            isBuild1: currentItem.isBuild,
            isBuild2: nextItem.isBuild,
          })
        }
      })
    }
  }
  console.log("[ newlineData ]-101", newlineData)
  tableData.value = newlineData
  // 以下处理导出数据
  exportData.value = {
    title: columns.value.map((item) => item.title),
    list: transformExportData(
      tableData.value,
      columns.value.map((item) => item.key)
    ),
  }
}
const loading = ref(false)
const handleExport = async () => {
  loading.value = true
  const res = await $api.exportCommon(exportData.value)
  loading.value = false
  utilsExportFile.exportFile(res, `${"充放电曲线数据"}.xlsx`)
}
</script>

<style lang="less" scoped>
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
</style>
